/**
 * 模态框工具脚本
 * 提供通用的模态框操作功能
 */

class ModalManager {
    /**
     * 初始化模态框管理器
     */
    constructor() {
        // 保存所有已打开的模态框引用
        this.openModals = new Set();
        
        // 绑定ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.openModals.size > 0) {
                // 关闭最后打开的模态框
                const lastModal = Array.from(this.openModals).pop();
                this.closeModal(lastModal);
            }
        });
    }
    
    /**
     * 打开模态框
     * @param {HTMLElement|string} modal - 模态框元素或模态框ID
     * @param {Object} options - 配置选项
     * @param {boolean} options.closeOnOutsideClick - 点击外部是否关闭模态框
     * @param {Function} options.onOpen - 打开后的回调函数
     * @param {Function} options.onClose - 关闭前的回调函数
     * @returns {HTMLElement} 模态框元素
     */
    openModal(modal, options = {}) {
        // 默认选项
        const defaultOptions = {
            closeOnOutsideClick: true,
            onOpen: null,
            onClose: null
        };
        
        // 合并选项
        const settings = { ...defaultOptions, ...options };
        
        // 获取模态框元素
        const modalElement = typeof modal === 'string' ? document.getElementById(modal) : modal;
        
        if (!modalElement) {
            console.error('Modal element not found');
            return null;
        }
        
        // 打开模态框
        modalElement.classList.add('active');
        this.openModals.add(modalElement);
        
        // 存储设置
        modalElement._modalSettings = settings;
        
        // 处理点击外部关闭
        if (settings.closeOnOutsideClick) {
            const handleOutsideClick = (e) => {
                if (e.target === modalElement) {
                    this.closeModal(modalElement);
                    modalElement.removeEventListener('click', handleOutsideClick);
                }
            };
            modalElement.addEventListener('click', handleOutsideClick);
        }
        
        // 绑定关闭按钮
        const closeBtn = modalElement.querySelector('.close-btn');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.closeModal(modalElement));
        }
        
        // 执行打开回调
        if (typeof settings.onOpen === 'function') {
            settings.onOpen(modalElement);
        }
        
        return modalElement;
    }
    
    /**
     * 关闭模态框
     * @param {HTMLElement|string} modal - 模态框元素或模态框ID
     * @returns {boolean} 是否成功关闭
     */
    closeModal(modal) {
        // 获取模态框元素
        const modalElement = typeof modal === 'string' ? document.getElementById(modal) : modal;
        
        if (!modalElement) {
            console.error('Modal element not found');
            return false;
        }
        
        // 执行关闭前回调
        if (modalElement._modalSettings && typeof modalElement._modalSettings.onClose === 'function') {
            // 如果回调返回false，则取消关闭
            if (modalElement._modalSettings.onClose(modalElement) === false) {
                return false;
            }
        }
        
        // 关闭模态框
        modalElement.classList.remove('active');
        this.openModals.delete(modalElement);
        
        return true;
    }
    
    /**
     * 创建并打开确认对话框
     * @param {string} message - 确认消息
     * @param {Object} options - 配置选项
     * @param {string} options.title - 对话框标题
     * @param {string} options.confirmText - 确认按钮文本
     * @param {string} options.cancelText - 取消按钮文本
     * @param {Function} options.onConfirm - 确认回调
     * @param {Function} options.onCancel - 取消回调
     * @returns {HTMLElement} 创建的对话框元素
     */
    confirm(message, options = {}) {
        // 默认选项
        const defaultOptions = {
            title: '确认',
            confirmText: '确定',
            cancelText: '取消',
            onConfirm: null,
            onCancel: null
        };
        
        // 合并选项
        const settings = { ...defaultOptions, ...options };
        
        // 创建确认对话框
        const dialogId = 'modal-confirm-' + Date.now();
        const dialog = document.createElement('div');
        dialog.id = dialogId;
        dialog.className = 'modal';
        dialog.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h2>${settings.title}</h2>
                    <button class="close-btn">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="18" y1="6" x2="6" y2="18"></line>
                            <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                    </button>
                </div>
                <div class="modal-body">
                    <p>${message}</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline cancel-btn">${settings.cancelText}</button>
                    <button class="btn btn-primary confirm-btn">${settings.confirmText}</button>
                </div>
            </div>
        `;
        
        // 添加到文档
        document.body.appendChild(dialog);
        
        // 打开对话框
        this.openModal(dialog, {
            onClose: () => {
                // 关闭后从DOM中移除对话框
                setTimeout(() => {
                    dialog.remove();
                }, 300);
                return true;
            }
        });
        
        // 绑定按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        const cancelBtn = dialog.querySelector('.cancel-btn');
        
        confirmBtn.addEventListener('click', () => {
            if (typeof settings.onConfirm === 'function') {
                settings.onConfirm();
            }
            this.closeModal(dialog);
        });
        
        cancelBtn.addEventListener('click', () => {
            if (typeof settings.onCancel === 'function') {
                settings.onCancel();
            }
            this.closeModal(dialog);
        });
        
        return dialog;
    }
    
    /**
     * 创建并打开提示对话框
     * @param {string} message - 提示消息
     * @param {Object} options - 配置选项
     * @param {string} options.title - 对话框标题
     * @param {string} options.buttonText - 按钮文本
     * @param {Function} options.onClose - 关闭回调
     * @returns {HTMLElement} 创建的对话框元素
     */
    alert(message, options = {}) {
        // 默认选项
        const defaultOptions = {
            title: '提示',
            buttonText: '确定',
            onClose: null
        };
        
        // 合并选项
        const settings = { ...defaultOptions, ...options };
        
        // 创建提示对话框
        const dialogId = 'modal-alert-' + Date.now();
        const dialog = document.createElement('div');
        dialog.id = dialogId;
        dialog.className = 'modal';
        dialog.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h2>${settings.title}</h2>
                    <button class="close-btn">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="18" y1="6" x2="6" y2="18"></line>
                            <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                    </button>
                </div>
                <div class="modal-body">
                    <p>${message}</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary ok-btn">${settings.buttonText}</button>
                </div>
            </div>
        `;
        
        // 添加到文档
        document.body.appendChild(dialog);
        
        // 打开对话框
        this.openModal(dialog, {
            onClose: () => {
                // 关闭后从DOM中移除对话框
                setTimeout(() => {
                    dialog.remove();
                }, 300);
                return true;
            }
        });
        
        // 绑定按钮事件
        const okBtn = dialog.querySelector('.ok-btn');
        
        okBtn.addEventListener('click', () => {
            if (typeof settings.onClose === 'function') {
                settings.onClose();
            }
            this.closeModal(dialog);
        });
        
        return dialog;
    }
}

// 创建全局模态框管理器实例
const modalManager = new ModalManager();

// 添加全局辅助函数
window.openModal = (modal, options) => modalManager.openModal(modal, options);
window.closeModal = (modal) => modalManager.closeModal(modal);
window.confirmDialog = (message, options) => modalManager.confirm(message, options);
window.alertDialog = (message, options) => modalManager.alert(message, options);

/**
 * 模态框工具类
 * 用于管理模态框的显示、隐藏和相关交互
 */
class Modal {
    /**
     * 初始化模态框
     * @param {string} modalId - 模态框的ID选择器
     */
    constructor(modalId) {
        this.modal = document.getElementById(modalId);
        this.isOpen = false;
        
        // 确保在页面点击时自动关闭模态框
        this.setupOutsideClickHandler();
    }
    
    /**
     * 显示模态框
     */
    open() {
        if (!this.modal) return;
        this.modal.classList.add('active');
        this.isOpen = true;
        document.body.style.overflow = 'hidden'; // 防止背景滚动
    }
    
    /**
     * 隐藏模态框
     */
    close() {
        if (!this.modal) return;
        this.modal.classList.remove('active');
        this.isOpen = false;
        document.body.style.overflow = '';
    }
    
    /**
     * 切换模态框显示状态
     */
    toggle() {
        if (this.isOpen) {
            this.close();
        } else {
            this.open();
        }
    }
    
    /**
     * 设置点击模态框外部区域关闭模态框
     */
    setupOutsideClickHandler() {
        if (!this.modal) return;
        
        this.modal.addEventListener('click', (event) => {
            // 如果点击的是模态框本身（背景），而不是内容区域
            if (event.target === this.modal) {
                this.close();
            }
        });
    }
    
    /**
     * 设置确认按钮的点击处理函数
     * @param {string} buttonId - 按钮的ID选择器
     * @param {Function} callback - 点击后的回调函数
     */
    setConfirmHandler(buttonId, callback) {
        const button = document.getElementById(buttonId);
        if (button) {
            button.addEventListener('click', () => {
                if (typeof callback === 'function') {
                    callback();
                }
                this.close();
            });
        }
    }
    
    /**
     * 设置取消按钮的点击处理函数
     * @param {string} buttonId - 按钮的ID选择器
     * @param {Function} callback - 点击后的回调函数(可选)
     */
    setCancelHandler(buttonId, callback) {
        const button = document.getElementById(buttonId);
        if (button) {
            button.addEventListener('click', () => {
                if (typeof callback === 'function') {
                    callback();
                }
                this.close();
            });
        }
    }
} 